package run.newbug.Pro2.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import run.newbug.Pro2.security.config.handler.*;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean("MyPasswordEncooder")
    public BCryptPasswordEncoder pwdEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.csrf().disable();
        http.formLogin().loginPage("/login.html")
                .loginProcessingUrl("/login")
//                .defaultSuccessUrl("/index.html")
                .successHandler(new MyRedirectAuthenticationSuccessHandler("/index.html"))
//                .successHandler(new JsonAuthenticationSuccessHandler())
//                .failureUrl("http://www.baidu.com")
                .failureHandler(new MyRedirectAuthenticationFailureHandler("http://www.baidu.com"));
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html?logout");

        http.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler())
                .authenticationEntryPoint(new MyAuthenticationEntryPoint());

        http.authorizeRequests()
                .antMatchers(
                        "/js/*",
                        "/css/*",
                        "/images/**",
                        "/bower_components/**",
                        "/login.html"
                )
                .permitAll()
                .anyRequest().authenticated();



    }
}